package com.shiro.config;

import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.mgt.WebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;

@Configuration
public class ShiroConfig {

    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("webSecurityManager") WebSecurityManager manager){
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        bean.setSecurityManager(manager);
        // 添加shiro的内置过滤器
        /*
            anon: 无需认证就可以登录
            authc:必须认证才能登录
            user: 必须拥有“记住我”这个功能
            perms:拥有对某个资源的权限才能访问
            role:拥有某个角色才能访问
         */
        LinkedHashMap<String, String> map = new LinkedHashMap<>();
        // 权限授权,访问url需要权限,支持通配符
        map.put("/level1/*", "perms[user:add]");
        map.put("/level2/*", "perms[all]");
        map.put("/level3/*", "authc");
        bean.setFilterChainDefinitionMap(map);
        // 设置未授权的请求
        bean.setUnauthorizedUrl("/noAuth");
        // 设置登录url映射
        bean.setLoginUrl("/toLogin");
        return  bean;
    }

    @Bean
    public DefaultWebSecurityManager webSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
        DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
        manager.setRealm(userRealm);
        return manager;
    }
    @Bean
    public UserRealm userRealm(){
        return  new UserRealm();
    }
}
